package com.itgaoshu.hospitalproject.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itgaoshu.hospitalproject.bean.DataGridView;
import com.itgaoshu.hospitalproject.bean.Menu;
import com.itgaoshu.hospitalproject.bean.TreeNode;
import com.itgaoshu.hospitalproject.bean.User;
import com.itgaoshu.hospitalproject.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sel")
public class MenuController {
    @Autowired
    private MenuService menuService;

    /**
     * 加载菜单管理菜单树
     * @param menu 菜单
     * @return 数据网格视图实体类DateGridView
     */
    @RequestMapping("toMenuMangerLeftTree")
    @ResponseBody
    public DataGridView toMenuMangerLeftTree(Menu menu) {
        //查询所有菜单那
        List<Menu> list = menuService.selectMenuAllList(menu);
        //将查询的菜单循环放入TreeNode
        List<TreeNode> nodes = new ArrayList<>();
        for (Menu menus : list) {
            int id = menus.getId();
            int pid = menus.getPid();
            String title = menus.getTitle();
            String icon = menus.getIcon();
            String href = menus.getHref();
            Boolean spread = menus.getSpread() == true;
            String target = menus.getTarget();
            nodes.add(new TreeNode(id, pid, title, icon, href, spread, target));
        }
        return new DataGridView(nodes);
    }

    /**
     * （模糊）查询所有菜单列表的方法
     * @param menu
     * @param page 页数
     * @param limit 每次显示几条信息
     * @return
     */
    @RequestMapping("selectMenuAllList")
    @ResponseBody
    public Object queryMenuAllList(Menu menu, int page, int limit) {

        PageHelper.startPage(page, limit);
        List<Menu> menus = menuService.selectMenuAllList(menu);
        PageInfo pageInfo = new PageInfo(menus);
        Map<String, Object> tableData = new HashMap<String, Object>();
        //这是layui要求返回的json数据格式
        tableData.put("code", 0);
        tableData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", pageInfo.getTotal());
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", pageInfo.getList());

        return tableData;
    }

    /**
     * 添加新菜单的方法
     * @param menu
     * @return 成功与否
     */
    @RequestMapping("addMenu")
    @ResponseBody
    public String addMenu(Menu menu) {

        int result = menuService.addMenu(menu);
        if (result > 0) {
            return "添加成功";
        } else {
            return "添加失败";
        }

    }

    /**
     * 通过pid检查菜单是否有子菜单
     * @param id pid
     * @return
     */
    @RequestMapping("checkMenuHasChildren")
    @ResponseBody
    public String checkMenuHasChildren(int id) {

        int pidNum = menuService.checkMenuHasChildren(id);
        if (pidNum < 1) {
            return "1";
        } else {
            return "0";
        }

    }

    /**
     * 根据id删除菜单
     * @param id
     * @return
     */
    @RequestMapping("deleteMenu")
    @ResponseBody
    public String deleteMenu(int id) {

        int result = menuService.deleteMenu(id);
        if(result > 0){
            return "true";
        }else{
            return "false";
        }

    }

    /**
     * 修改菜单的方法
     * @param menu 菜单类
     * @return
     */
    @RequestMapping("updateMenu")
    @ResponseBody
    public String updateMenu(Menu menu) {

        int result = menuService.updateMenu(menu);
        if(result > 0){
            return "修改成功";
        }else{
            return "修改失败";
        }
    }

    //跳转登录的页面
    @RequestMapping("toLogin")
    public String toLogin(){
        return "view/login";
    }

    //进行登录认证的页面
    @RequestMapping("login")
    public String login1(String loginname, String pwd, Model model, HttpServletRequest request){
        //建立subject
        Subject subject = SecurityUtils.getSubject();
        //封装token凭证
        UsernamePasswordToken token = new UsernamePasswordToken(loginname,pwd);
        try{
            //进行认证
            subject.login(token);
            User user = menuService.login(loginname);
            //将user对象封装到shiro的session中以便认证之后进行获取
            request.getSession().setAttribute("user",user);
            model.addAttribute("loginname",user.getRealname());
            //将id传过去在页面中有关于个人信息的，然后要通过id来获取个人资料
            model.addAttribute("id",user.getUserid());
            //把用户放进session中,在进行住院管理的住院登记中要获取当前用户的进行患者登记
            request.getSession().setAttribute("yonghu",user.getRealname());
            return "view/index";//跳转到首页
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名不存在或者用户名不正确");
            return "view/login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不正确");
            return "view/login";
        }
    }

    //加载首页菜单的导航栏
    @RequestMapping("toTreeLoad")
    @ResponseBody
    public List<TreeNode> toTreeLoad(HttpServletRequest request){
        //获取用户登录的id来获取不同的菜单,在用户登录时已经封装到了session中
        User user = (User) request.getSession().getAttribute("user");
        //根据用户的id不同来获取不同的菜单，赋予不同的权限
        List<Menu> menus = menuService.selectMenuById(user.getUserid());

        //创建list集合，将不同菜单放入到nodes中去
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        for(Menu menu:menus){
            nodes.add(new TreeNode(menu.getId(),
                    menu.getPid(),menu.getTitle(),
                    menu.getIcon(),menu.getHref(),
                    menu.getSpread(),menu.getTarget()));
        }
        //组装菜单
        List<TreeNode> treeNodes = new ArrayList<>();
        for(TreeNode n1:nodes){
            if(n1.getPid()==1){//此为父级的菜单
                treeNodes.add(n1);
            }
            for(TreeNode n2:nodes){
                if(n2.getPid()==n1.getId()){//遍历这个树结点，
                    // 比较n2树的结点的上一级结点和n1树的结点，如果相同，表明n2结点是n1结点的子节点
                    //将n2放到n1 的孩子结点中，表明n2结点为N1结点的下一级结点
                    n1.getChildren().add(n2);
                }
            }
        }
        return treeNodes;
    }

    //退出的方法
    @RequestMapping("exit")
    public String exit(HttpServletRequest request){
        //从session中移除当前用户的对象
        request.getSession().removeAttribute("user");
        return "redirect:/sel/toLogin";//退出到登录页面

    }


}
